import router, { asyncRoutes } from './router'
import nprogress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from './store'

nprogress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转到主页
      next('/') // 中转到主页
      // next（地址）并没有执行后置守卫
      nprogress.done()
      return
    }
    if (!store.getters.name) {
      await store.dispatch('user/getUserInfoAction')
      const user = store.state.user
      const menus = user.userInfo.roles.menus
      console.log(asyncRoutes)

      const newList = asyncRoutes.filter(item => {
        return menus.includes(item.name)
      })
      router.addRoutes([...newList, { path: '*', redirect: '/404', hidden: true }])
      store.commit('user/setRoutes', newList)
      next(to.path)
    }
    next() // 放行
    return
  }
  // 没有token
  if (whiteList.includes(to.path)) {
    next()
  } else {
    next('/login') // 中转到登录页
    nprogress.done()
  }
})
router.afterEach(() => {
  // finish progress bar
  nprogress.done()
})
